<template>
  <div class="app-container">
    <el-card class="box-card" :body-style="{ 'min-height': 'calc(100vh - 110px)',padding: '24px' }">
      <div class="comp-tree">
        <el-input
          v-model="filterText"
          placeholder="输入关键字进行过滤"
          suffix-icon="el-icon-search"
          clearable
          style="width:30%"
        />

        <el-tree
          ref="tree"
          v-loading="loading"
          :data="treeData"
          node-key="id"
          default-expand-all
          :filter-node-method="filterNode"
          :expand-on-click-node="false"
          :props="treeProps"
          style="margin-top: 20px;"
        >
          <!-- <span slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button
                type="text"
                size="mini"
                icon="el-icon-plus"
                @click="() => append(data)"
              />
              <el-button
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="() => remove(node, data)"
              />
            </span>
          </span> -->
          <!-- <span slot-scope="{ node, data }" class="custom-tree-node">
            <span>{{ node.label }}</span>
            <el-dropdown
              trigger="click"
              @command="command => handleCommand(command, data, node)"
            >
              <span class="el-dropdown-link">
                <i class="el-icon-more" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="insert">新增</el-dropdown-item>
                <el-dropdown-item command="modify">编辑</el-dropdown-item>
                <el-dropdown-item command="delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </span> -->
          <div slot-scope="{ node, data }" class="comp-tr-node">
            <template>
              <span class="comp-tr-node--name">
                {{ node.label }}
              </span>
              <!-- 按钮 -->
              <span class="comp-tr-node--btns">
                <!-- 新增 -->
                <el-button
                  icon="el-icon-plus"
                  size="mini"
                  circle
                  type="primary"
                  @click="handleCreate(data, node)"
                />

                <!-- 编辑 -->
                <el-button
                  v-if="!data.noEdit"
                  icon="el-icon-edit"
                  size="mini"
                  circle
                  type="info"
                  @click="handleUpdate(data, node)"
                />

                <!-- 删除 -->
                <el-button
                  v-if="!data.noEdit && (!data.children || data.children.length ===0)"
                  icon="el-icon-delete"
                  size="mini"
                  circle
                  type="danger"
                  @click="handleDelete(data, node)"
                />
              </span>
            </template>
          </div>
        </el-tree>
      </div>
    </el-card>

    <!-- dialog -->
    <div v-if="dialogFormVisible">
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="30%">
        <el-form ref="dataForm" :rules="rules" :model="view" label-position="left" label-width="90px" style="width: 80%; margin-left:50px;">
          <el-form-item label="菜单名称" prop="viewName">
            <el-input v-model="view.viewName" placeholder="请输入菜单名称" />
          </el-form-item>
          <el-form-item label="菜单类型" prop="viewType">
            <el-radio-group v-model="view.viewType">
              <el-radio label="menu">菜单</el-radio>
              <el-radio label="button">按钮</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="菜单图标" prop="viewIcon">
            <el-input v-model="view.viewIcon" placeholder="请输入菜单图标" />
          </el-form-item>
          <el-form-item label="菜单路径" prop="viewPath">
            <el-input v-model="view.viewPath" placeholder="请输入菜单路径" />
          </el-form-item>
          <el-form-item label="组件名称" prop="viewComponent">
            <el-input v-model="view.viewComponent" placeholder="请输入组件名称" />
          </el-form-item>
          <el-form-item label="排序" prop="viewOrder">
            <el-input v-model="view.viewOrder" placeholder="请输入排序" />
          </el-form-item>
          <el-form-item label="资源" prop="permissionId">
            <SelectTree
              ref="treeSelect"
              v-model="view.permissionId"
              :styles="styles"
              :select-params="selectParams"
              :tree-params="treeParams"
              @searchFun="_searchFun"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import SelectTree from '@/components/Tree/SelectTree'
import { getPermissionTreeData } from '@/api/permission.js'
import { getViewTreeData, addView, updateView, deleteView } from '@/api/view.js'
import { convertTreeData } from '@/utils'
// import _ from 'lodash'

// import { mapGetters } from 'vuex'

export default {
  name: 'MenuManagement',
  components: { SelectTree },
  data() {
    return {
      treeData: [],
      currentData: null,
      treeProps: {
        label: 'viewName',
        children: 'children'
      },
      styles: {
        width: '100%'
      },
      selectParams: {
        clearable: true,
        placeholder: '请选择资源'
      },
      treeParams: {
        clickParent: false,
        filterable: true,
        'check-strictly': false,
        'default-expand-all': false,
        'expand-on-click-node': false,
        'highlight-current': true,
        // 'render-content': this._renderFun,
        data: [],
        props: {
          children: 'children',
          label: 'permissionName',
          // disabled: 'disabled',
          value: 'id'
        }
      },
      filterText: '',
      loading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      view: {
        viewName: '',
        viewType: '',
        viewIcon: '',
        viewPath: '',
        viewComponent: '',
        viewOrder: '',
        permissionId: ''
      },
      rules: {
        viewName: [{ required: true, message: '菜单名称不能为空', trigger: 'change' }],
        viewType: [{ required: true, message: '菜单类型不能为空', trigger: 'change' }],
        permissionId: [{ required: true, message: '资源不能为空', trigger: 'change' }]
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getViewList()
    this.getResourceList()
  },
  methods: {
    _searchFun(val) {
      this.$refs.treeSelect.filterFun(val)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    resetResourceProp() {
      this.view = {
        id: '',
        parentId: '',
        viewName: '',
        viewType: '',
        viewIcon: '',
        viewPath: '',
        viewComponent: '',
        viewOrder: '',
        permissionId: ''
      }
    },
    handleCommand(command, data, node) {
      const handler = {
        insert: this.handleCreate,
        modify: this.handleUpdate,
        delete: this.handleDelete
      }
      if (handler[command]) {
        handler[command](data, node)
      }
    },
    getViewList() {
      this.loading = true
      getViewTreeData().then(response => {
        const res = response.retBody
        if (res && res.length > 0) {
          const viewTree = convertTreeData(res)
          viewTree[0].noEdit = true
          this.treeData.length = 0
          this.treeData = [...viewTree]
        }
      }).finally(() => {
        setTimeout(() => {
          this.loading = false
        }, 1 * 1000)
      })
    },
    getResourceList() {
      getPermissionTreeData().then(response => {
        const res = response.retBody
        if (res && res.length > 0) {
          const permissionTree = convertTreeData(res)
          this.treeParams.data.length = 0
          this.treeParams.data = [...permissionTree]
        }
      })
    },
    handleCreate(data, node) {
      this.resetResourceProp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.view.parentId = data.id
      this.currentData = { ...data }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(data, node) {
      this.view = { ...data }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.currentData = { ...data }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(data, node) {
      this.$confirm('确定要删除该条菜单信息?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteView(data.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除菜单信息成功',
            type: 'success',
            duration: 1000
          })
          const parent = node.parent
          const children = parent.data.children || parent.data
          const index = children.findIndex(d => d.id === data.id)
          children.splice(index, 1)
        })
      }).catch(() => {

      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addView(this.view).then(response => {
            const res = response.retBody
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新增菜单成功',
              type: 'success',
              duration: 1500
            })
            this.view.id = res
            if (!this.currentData.children) {
              this.$set(this.currentData, 'children', [])
            }
            this.currentData.children.push(this.view)
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateView(this.view.id, this.view).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改菜单信息成功',
              type: 'success',
              duration: 1500
            })
            this.currentData.viewName = this.view.viewName
            this.currentData.viewType = this.view.viewType
            this.currentData.viewIcon = this.view.viewIcon
            this.currentData.viewPath = this.view.viewPath
            this.currentData.viewComponent = this.view.viewComponent
            this.currentData.viewOrder = this.view.viewOrder
            this.currentData.permissionId = this.view.permissionId
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
 .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 10px;
  }

  /* common */
	.show-btns{
		opacity: 1;
	}
	/* common end */
	.comp-tree{
		width: 100%;
		max-width: 700px;
		max-height: 80vh;
		padding: 2em;
		overflow: auto;
		// 顶部按钮
		.comp-tr-top{
			width: 100px;
			margin-bottom: 2em;
		}
		// 自定义节点
		.comp-tr-node{
			// label
			.comp-tr-node--name{
				display: inline-block;
				line-height: 40px;
				min-height: 40px;
				// 新增
				&.is-new{
					font-weight: bold;
				}
			}
			// button
			.comp-tr-node--btns{
				margin-left: 10px;
				opacity: 0;
				transition: opacity .1s;
				.el-button{
					transform: scale(0.8);// 缩小按钮
					& + .el-button{
						margin-left: -1px;
					}
				}
			}
		}
		// 高亮显示按钮
		.is-current{
			&>.el-tree-node__content{
				.comp-tr-node--btns{
					@extend .show-btns;
				}
			}
		}
		// 悬浮显示按钮
		.el-tree-node__content{
			&:hover{
				.comp-tr-node--btns{
					@extend .show-btns;
				}
			}
		}
	}
</style>
